#include "socketserver.h"
#include <QFile>
#include <QCoreApplication>
#include <QDir>
#include "command.h"

SocketServer::SocketServer(QString connect_name):m_connect_name(connect_name)
{
    m_connect_name = QCoreApplication::applicationDirPath() +QDir::separator()+connect_name;
    QFile::remove(m_connect_name);
    m_local_server = new QLocalServer();
    connect(m_local_server,SIGNAL(newConnection()),this,SLOT(OnConnection()));
}

SocketServer::~SocketServer()
{
    if (nullptr != m_local_server) {
        m_local_server->removeServer(m_connect_name);
        delete m_local_server;
        m_local_server = nullptr;
    }
}

bool SocketServer::startListen()
{
    return m_local_server->listen(m_connect_name);
}

void SocketServer::close() {
    m_local_server->close();
}

void SocketServer::OnConnection()
{
    QLocalSocket *socket=m_local_server->nextPendingConnection();
    SocketClient *client=new SocketClient(socket->socketDescriptor(),socket);
    connect(client,SIGNAL(Disconnect(qintptr)),this,SLOT(OnClientDisconnect(qintptr)));
    connect(client,SIGNAL(BackGroundCommand(Command)),this,SLOT(OnBackGroundCommand(Command)));
    m_client_hash.insert(socket->socketDescriptor(),client);
}

void SocketServer::OnClientDisconnect(qintptr socketDescriptor)
{
    delete m_client_hash[socketDescriptor];
    m_client_hash.remove(socketDescriptor);
}

void SocketServer::OnBackGroundCommand(Command command){
    switch (command.target) {
    case UpdateTarget::DoorNo:
        emit DoorNoChanged();
        break;
    case UpdateTarget::QrCode:
        emit QrCodeChanged();
        break;
    case UpdateTarget::Pic:
        emit PicChanged();
        break;
     case UpdateTarget::Interval:
        emit IntervalChanged();
        break;
    }
}
